package com.pactera.miyuangroup.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.db.entity.LoginRole;
import com.pactera.miyuangroup.db.entity.RoleMenu;
import com.pactera.miyuangroup.service.LoginRoleService;
import com.pactera.miyuangroup.service.RoleMenuService;
import com.pactera.miyuangroup.vo.convertor.MenuConvert;
import com.pactera.miyuangroup.vo.response.web.MenuRes;
import com.pactera.miyuangroup.vo.response.web.OrganizationRes;
import com.pactera.miyuangroup.vo.response.web.TreeMenuRes;
import lombok.extern.slf4j.Slf4j;

import com.pactera.miyuangroup.db.entity.Menu;
import com.pactera.miyuangroup.db.mapper.MenuMapper;
import com.pactera.miyuangroup.service.MenuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统菜单 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class MenuServiceImp extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuConvert menuConvert;
    @Autowired
    private LoginRoleService loginRoleService;
    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 根据用户ID 获取树形菜单
     * 用户ID 可为空，为空查询所有
     *
     * @param userId
     * @return
     */
    @Override
    public List<TreeMenuRes> getTreeMenuList(String userId) {

        EntityWrapper<Menu> entityWrapper = null;

        //查询根节点
        entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("pid", Constants.SYS_ROOT);
        List<Menu> rootMenus = selectList(entityWrapper);


        //生成树形结构数据
        List<Menu> menus = new ArrayList<>();

        //判断是否查询用户菜单
        if (StringUtils.isNotBlank(userId)) {
            //查询用户所有角色
            List<String> menuIds = getUserAllMenu(userId);
            entityWrapper = new EntityWrapper<>();
            entityWrapper.in("id", menuIds).or("pid={0}", Constants.SYS_ROOT).orderBy("sort");
            menus = selectList(entityWrapper);
        } else {
            //查询所有菜单
            entityWrapper = new EntityWrapper<>();
            entityWrapper.orderBy("sort");
            menus = selectList(entityWrapper);
        }

        List<TreeMenuRes> lists = new ArrayList<TreeMenuRes>();
        for (Menu m : rootMenus) {
            TreeMenuRes childArray = null;
            childArray = menuConvert.convert2TreeMenuRes(m);
            childArray.setChildren(menuChild(menus, m.getId()));
            lists.add(childArray);
        }
        return lists;
    }


    /**
     * 根据角色ID 查询菜单
     *
     * @param roleId
     * @return
     */
    @Override
    public List<MenuRes> getMenuByRoleId(String roleId) {

        //查询角色对应菜单
        EntityWrapper<RoleMenu> roleMenuEntityWrapper = new EntityWrapper<>();
        roleMenuEntityWrapper.eq("role_id", roleId);
        List<String> menuIds = roleMenuService.selectList(roleMenuEntityWrapper).stream().map(rm -> {
            return rm.getMenuId();
        }).distinct().collect(Collectors.toList());
        List<MenuRes> mr = null;
        if (menuIds.size() > 0) {
            EntityWrapper<Menu> entityWrapper = new EntityWrapper<>();
            entityWrapper.in("id", menuIds).orderBy("sort");
            List<Menu> menus = selectList(entityWrapper);
            mr = menuConvert.convert2MenuRes(menus);
        }
        return mr;
    }


    /**
     * 查询用户所有菜单
     *
     * @param userId
     * @return
     */
    private List<String> getUserAllMenu(String userId) {
        //查询用户所有角色
        EntityWrapper<LoginRole> loginRoleEntityWrapper = new EntityWrapper<>();
        loginRoleEntityWrapper.eq("login_user_id", userId);
        List<String> roles = loginRoleService.selectList(loginRoleEntityWrapper).stream().map(lr -> {
            return lr.getRoleId();
        }).distinct().collect(Collectors.toList());

        //查询角色对应菜单
        EntityWrapper<RoleMenu> roleMenuEntityWrapper = new EntityWrapper<>();
        roleMenuEntityWrapper.in("role_id", roles);
        List<String> menus = roleMenuService.selectList(roleMenuEntityWrapper).stream().map(rm -> {
            return rm.getMenuId();
        }).distinct().collect(Collectors.toList());
        return menus;
    }

    /**
     * 递归 生成菜单树
     *
     * @param m
     * @param id
     * @return
     */
    private List<TreeMenuRes> menuChild(List<Menu> m, String id) {
        List<TreeMenuRes> lists = new ArrayList<TreeMenuRes>();
        lists = m.stream().filter(o -> id.equals(o.getPid())).map(c -> {
            TreeMenuRes childArray = null;
            childArray = menuConvert.convert2TreeMenuRes(c);
            childArray.setChildren(menuChild(m, c.getId()));
            return childArray;
        }).collect(Collectors.toList());
        if (lists.size() <= 0) {
            lists = null;
        }
        return lists;
    }
}
